package com.xbongbong.workflow.service.strategy.data.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.enums.TaskTypeEnum;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.log.constant.CrmLogMemoConstant;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.pro.customercommunicate.pojo.dto.CustomerDynamicAddDTO;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.fund.enums.ModelTypeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.invoice.pojo.InvoiceCommonSavePojo;
import com.xbongbong.pro.invoice.pojo.InvoiceRelationshipEditPojo;
import com.xbongbong.pro.message.pojo.dto.ConsistencySyncRabbitMqDTO;
import com.xbongbong.pro.user.pojo.ReturnUserAndDepartmentPojo;
import com.xbongbong.pro.workflow.enums.WorkflowOperateEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.domain.entity.InvoiceRelationshipEntity;
import com.xbongbong.saas.domain.entity.ext.InvoiceEntityExt;
import com.xbongbong.saas.enums.ProjectLogEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.InvoiceEnum;
import com.xbongbong.saas.enums.business.RefTypeEnum;
import com.xbongbong.saas.help.InvoiceHelp;
import com.xbongbong.saas.help.ReceivablesHelper;
import com.xbongbong.saas.model.CustomerExpressModel;
import com.xbongbong.saas.model.CustomerInvoiceModel;
import com.xbongbong.saas.model.FundSetModel;
import com.xbongbong.saas.model.InvoiceModel;
import com.xbongbong.saas.model.InvoiceRelationshipModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.service.ConsistencySyncService;
import com.xbongbong.saas.service.CustomerCommunicateService;
import com.xbongbong.saas.service.InvoiceService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.util.OwnerIdAndCoUserIdUtil;
import com.xbongbong.workflow.domain.entity.WorkflowBackupDataEntity;
import com.xbongbong.workflow.model.WorkflowBackupDataModel;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.User;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.pojo.dto.WorkflowReceivablesDTO;
import com.xbongbong.workflow.service.strategy.data.AbstractWorkflowDataStrategy;
import com.xbongbong.workflow.service.strategy.data.WorkflowDataProcessStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;

/**
 *
 * @author 魏荣杰
 *
 */
@Service
@Slf4j
public class WorkflowInvoiceStrategy extends AbstractWorkflowDataStrategy implements WorkflowDataProcessStrategy {

    @Resource
    private InvoiceModel invoiceModel;
    @Resource
    private WorkflowBackupDataModel workflowBackupDataModel;
    @Resource
    private CustomerInvoiceModel customerInvoiceModel;
    @Resource
    private CustomerExpressModel customerExpressModel;
    @Resource
    private InvoiceRelationshipModel invoiceRelationshipModel;
    @Resource
    private InvoiceHelp invoiceHelp;
    @Resource
    private UserModel userModel;
    @Resource
    private InvoiceService invoiceService;
    @Resource
    private FundSetModel fundSetModel;
    @Resource
    private ReceivablesHelper receivablesHelper;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private CustomerCommunicateService customerCommunicateService;
    @Resource
    private ConsistencySyncService consistencySyncService;

    @Override
    public List<Integer> type() {
        return Collections.singletonList(XbbRefTypeEnum.INVOICE.getCode());
    }

    @Override
    public void save(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);

        String corpid = workflowTransferPOJO.getCorpid();
        Data pojoData = workflowTransferPOJO.getData();
        JSONObject data = pojoData.getData();
        Long dataId = pojoData.getId();
        User user = workflowTransferPOJO.getUser();

        Integer isImport = workflowTransferPOJO.getIsImport();
        boolean isRed = false;
        if(data.containsKey(InvoiceEnum.ORIGIN_ID.getAttr())){
            Long originId = FastJsonHelper.getLongOrDefaultFromFormData(data,InvoiceEnum.ORIGIN_ID.getAttr(),0L);
            if(originId >0){
                isRed = true;
            }
        }
        boolean isEnable = false;
        Long originId = FastJsonHelper.getLongOrDefaultFromFormData(data, InvoiceEnum.ORIGIN_ID.getAttr(), 0L);
        //红冲发票新建工作流审批通过的时候才会改原始发票这两个字段
        if (isRed) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(InvoiceEnum.HAS_RED.getAttr(), BasicConstant.ONE);
            UpdateDataEntity updateData = ExplainUtil.getUpdateData(originId, jsonObject, corpid);
            invoiceModel.updateBatch(Collections.singletonList(updateData), corpid);

            jsonObject = new JSONObject();
            jsonObject.put(InvoiceEnum.IS_RED.getAttr(), BasicConstant.ONE);
            UpdateDataEntity updateData1 = ExplainUtil.getUpdateData(dataId, jsonObject, corpid);
            invoiceModel.updateBatch(Collections.singletonList(updateData1), corpid);
        }

        if(CollectionsUtil.isEmpty(saasNeedRedundantAttrPojo.getAmountDetail()) && Objects.equals(isImport, BasicConstant.ZERO)){
            //兼容老数据,老数据走导入的老逻辑
            isImport = BasicConstant.ONE;
        }
        Object contractNoObject = data.get(InvoiceEnum.CONTRACT_ID_LINK_TEXT.getAttr());
        List<String> contractNoList = null;
        if(Objects.nonNull(contractNoObject)){
            if(contractNoObject instanceof String[]){
                String[]  purchaseNos = (String[]) contractNoObject;
                contractNoList = new ArrayList<>(Arrays.asList(purchaseNos));
            }else if(contractNoObject instanceof List){
                contractNoList = (List<String>) contractNoObject;
            }
        }else {
            contractNoList = new ArrayList<>();
        }
        InvoiceRelationshipEditPojo invoiceRelationshipEditPojo = invoiceHelp.getAddOrDeleteRelationship(data, data, corpid, dataId);
        //开票的金额
        Double totalMoney = getDoubleOrDefaultFromFormData(data, InvoiceEnum.TOTAL_MONEY.getAttr(), 0D);
        //-------------------------------关系表存储公共的属性
        Long now = (long) DateUtil.getInt();
        Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(data, InvoiceEnum.CUSTOMER_NAME.getAttr(), 0L);
        String customerName = FastJsonHelper.getStringOrDefaultFromFormData(data, InvoiceEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), "");


        // 2020 4/24 新增小功能 新建销项发票 客户没有填发票信息 和 寄送地址就 存到客户发票信息表 和 寄送表
        JSONArray customerInvoice =  FastJsonHelper.getJsonArrOrDefaultFromFormData(data, InvoiceEnum.CUSTOMER_INVOICE.getAttr(),new JSONArray());
        JSONArray customerExpress =  FastJsonHelper.getJsonArrOrDefaultFromFormData(data, InvoiceEnum.CUSTOMER_EXPRESS.getAttr(),new JSONArray());
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",corpid);
        param.put("customerId",customerId);
        param.put("del",BasicConstant.ZERO);
        if(CollectionsUtil.isNotEmpty(customerInvoice)){
            Integer count = customerInvoiceModel.getEntitysCount(param);
            if(count <= BasicConstant.ZERO){
                invoiceHelp.saveCustomerInvoiceAndExpress(corpid, customerId, user.getUserId(), user.getName(), customerInvoice, null);
            }
        }
        if(CollectionsUtil.isNotEmpty(customerExpress)){
            Integer count = customerExpressModel.getEntitysCount(param);
            if(count <= BasicConstant.ZERO){
                invoiceHelp.saveCustomerInvoiceAndExpress(corpid, customerId,user.getUserId(), user.getName(), null, customerExpress);
            }
        }


        InvoiceEntityExt invoiceEntityExt = invoiceModel.getByKey(dataId, corpid);
        UserEntity userEntity = userModel.getByKey(user.getUserId(), corpid);
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(userEntity, userVO);

        InvoiceCommonSavePojo invoiceCommonSavePojo = new InvoiceCommonSavePojo(invoiceRelationshipEditPojo.getContractIdList(), corpid, dataId, originId, now, saasNeedRedundantAttrPojo, true, isEnable, isImport, isRed, totalMoney, saasNeedRedundantAttrPojo.getAmountDetail(), invoiceEntityExt, userVO, pojoData.getBusinessType(), pojoData.getSubBusinessType());
        boolean contractInvoiceFlag = saasNeedRedundantAttrPojo.isHasContract() && !saasNeedRedundantAttrPojo.isHasPayment() && !saasNeedRedundantAttrPojo.isHasPaymentSheet();
        boolean paymentInvoiceFlag = saasNeedRedundantAttrPojo.isHasPayment() && saasNeedRedundantAttrPojo.isHasContract() && !saasNeedRedundantAttrPojo.isHasPaymentSheet();
        boolean paymentSheetInvoiceFlag = saasNeedRedundantAttrPojo.isHasPaymentSheet() && saasNeedRedundantAttrPojo.isHasContract() && !saasNeedRedundantAttrPojo.isHasPayment();
        boolean isPrePaymentSheetFlag = saasNeedRedundantAttrPojo.isPrePaymentSheet();
//        try {
        try {
            String lang = LocaleContextHolder.getLocale().toString();
            if(saasNeedRedundantAttrPojo.isContractUnion() || contractInvoiceFlag) {
                //合同不为空 其他为空 合同合并开票
                invoiceCommonSavePojo.setRefIdList(invoiceRelationshipEditPojo.getContractIdList());
                invoiceCommonSavePojo.setRefTypeEnum(RefTypeEnum.CONTRACT);
                invoiceCommonSavePojo.setContractNos(contractNoList);
                invoiceCommonSavePojo.setCustomerId(customerId);
                invoiceCommonSavePojo.setCustomerName(customerName);
                invoiceService.invoiceCommonSaveHandle(invoiceCommonSavePojo);
            } else if(saasNeedRedundantAttrPojo.isPaymentUnion() || paymentInvoiceFlag) {
                invoiceCommonSavePojo.setRefIdList(invoiceRelationshipEditPojo.getPaymentIdList());
                invoiceCommonSavePojo.setRefTypeEnum(RefTypeEnum.PAYMENT);
                invoiceCommonSavePojo.setContractNos(contractNoList);
                invoiceCommonSavePojo.setCustomerId(customerId);
                invoiceCommonSavePojo.setCustomerName(customerName);
                invoiceService.invoiceCommonSaveHandle(invoiceCommonSavePojo);
            } else if(saasNeedRedundantAttrPojo.isPaymentSheetUnion() || paymentSheetInvoiceFlag || isPrePaymentSheetFlag) {
                invoiceCommonSavePojo.setRefIdList(invoiceRelationshipEditPojo.getPaymentSheetIdList());
                invoiceCommonSavePojo.setRefTypeEnum(RefTypeEnum.PAYMENTSHEET);
                invoiceCommonSavePojo.setContractNos(contractNoList);
                invoiceCommonSavePojo.setCustomerId(customerId);
                invoiceCommonSavePojo.setCustomerName(customerName);
                invoiceService.invoiceCommonSaveHandle(invoiceCommonSavePojo);
            } else {
                InvoiceRelationshipEntity invoiceRelationshipEntity = invoiceHelp.buildNewInvoiceRelation(false, dataId, now,customerId,customerName, corpid,totalMoney,0L,"",0L, "",0L, "",0);
                if (Objects.nonNull(invoiceRelationshipEntity)) {
                    try {
                        invoiceRelationshipModel.insert(invoiceRelationshipEntity);
                    } catch (Exception e) {
                        log.error("插入发票关系实体表出错", e);
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                    }
                }//消息推送
                invoiceHelp.invoiceMessagePushHandle(invoiceCommonSavePojo);
            }

        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowInvoiceStrategy.save 发票");
        }

//        } catch (XbbException e) {
//            rollBack4LinkEs(null, corpid, invoiceRelationshipEditPojo.getContractIdList(), invoiceRelationshipEditPojo.getPaymentIdList(), invoiceRelationshipEditPojo.getPaymentSheetIdList());
//            log.error("invoiceServiceImp.afterSave 执行出错：", e);
//            throw e;
//        }catch (Exception e){
//            rollBack4LinkEs(null, corpid, invoiceRelationshipEditPojo.getContractIdList(), invoiceRelationshipEditPojo.getPaymentIdList(), invoiceRelationshipEditPojo.getPaymentSheetIdList());
//            log.error("invoiceServiceImp.afterSave 执行出错：", e);
//            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
//        }

//        if(isRed){
//            List<PaasFormDataEntityExt> paasFormDataEntityExts = paymentService.getReceivablesBySourceIdIn(corpid, ModelTypeEnum.INVOICE.getXbbRefTypeEnum().getCode(), Collections.singletonList(originId));
//            if(CollectionsUtil.isNotEmpty(paasFormDataEntityExts)){
//                saasFormSaveDTO.setHasReceivables(BasicConstant.ONE);
//            }
//        }
        //获取当前处于什么模式

        Long modelType = fundSetModel.getModelType(corpid,XbbRefTypeEnum.CRM);
        if(Objects.equals(modelType, ModelTypeEnum.INVOICE.getCode())){
            if(!isRed) {
                JSONArray contractIdArray = data.getJSONArray(InvoiceEnum.CONTRACT_ID.getAttr());
                if (CollectionsUtil.isNotEmpty(contractIdArray)) {
                    SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
                    saasFormSaveDTO.setCorpid(corpid);
                    saasFormSaveDTO.setAmountDetail(saasNeedRedundantAttrPojo.getAmountDetail());
                    saasFormSaveDTO.setNewPaasFormDataEntity(invoiceEntityExt);
                    saasFormSaveDTO.setBusinessType(pojoData.getBusinessType());

                    List<ReturnUserAndDepartmentPojo> ownList = new ArrayList<>();
                    ownList.add(new ReturnUserAndDepartmentPojo(data.getString(FieldTypeEnum.OWNERID.getAlias())));
                    List<ReturnUserAndDepartmentPojo> coUserList = new ArrayList<>();
                    coUserList.add(new ReturnUserAndDepartmentPojo(data.getString(FieldTypeEnum.COUSERID.getAlias())));

                    saasFormSaveDTO.setOwnerId(ownList);
                    saasFormSaveDTO.setCoUserId(coUserList);
                    saasFormSaveDTO.setProcessCreatorId(user.getUserId());
                    saasFormSaveDTO.setIsImport(isImport);
                    saasFormSaveDTO.setLoginUser(userVO);


                    receivablesHelper.createReceivablesHandle(saasFormSaveDTO, modelType, null);
//                    receivablesHelper.createReceivablesHandle(saasFormSaveDTO, modelType, null);
                }
            }
        }

        // 更新退回退款关联的发票
        Long refundId = data.getLong(PaasConstant.REFUND_ID);
        if (refundId != null){
            invoiceHelp.updateRefundInvoiceId(refundId, dataId, data, corpid);
        }

        try {
            if(isNotDistributeBusinessType(workflowTransferPOJO)) {
                String memo;
                String communicateMemo;
                if (Objects.equals(workflowTransferPOJO.getIsImport(), BasicConstant.ONE)) {
                    memo = CrmLogMemoConstant.DYNAMIC_USER_IMPORT;
                } else {
                    memo = CrmLogMemoConstant.DYNAMIC_USER_ADD;
                }
                PaasFormEntity paasForm = proFormHelp.getPaasForm(pojoData.getFormId(), pojoData.getBusinessType(), corpid);
                String paasFormName = XbbRefTypeEnum.INVOICE.getName();
                if (Objects.nonNull(paasForm)) {
                    paasFormName = paasForm.getName();
                }
                String serialNo = invoiceEntityExt.getSerialNo();
                String creatorName = Objects.nonNull(userEntity) ? userEntity.getName() : "";
                communicateMemo = String.format(I18nMessageUtil.getMessage(memo), creatorName, paasFormName, serialNo);

                CustomerDynamicAddDTO customerDynamicAddDTO = new CustomerDynamicAddDTO();
                customerDynamicAddDTO.setCorpid(corpid);
                customerDynamicAddDTO.setUserId(user.getUserId());
                customerDynamicAddDTO.setCustomerId(data.getLong(InvoiceEnum.CUSTOMER_NAME.getAttr()));
                customerDynamicAddDTO.setContractIds(FastJsonHelper.getTransferTypesFromData(data, InvoiceEnum.CONTRACT_ID.getAttr(), Long.class));
                customerDynamicAddDTO.setMemo(communicateMemo);
                customerDynamicAddDTO.setCommunicateBusinessText(serialNo);
                customerDynamicAddDTO.setCommunicateBusinessType(XbbRefTypeEnum.INVOICE.getCode());
                customerDynamicAddDTO.setDataId(dataId);
                customerDynamicAddDTO.setLogType(ProjectLogEnum.INVOICE_CREATE.getSubType());
                customerDynamicAddDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                customerCommunicateService.addCustomerDynamic(customerDynamicAddDTO);
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowInvoiceStrategy.save", e);
        }
        addLinkDataDynamic(workflowTransferPOJO);
        // api
        apiHook(workflowTransferPOJO);
        // log
        afterSaveLog(workflowTransferPOJO);
    }

    @Override
    public void update(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);

        String corpid = workflowTransferPOJO.getCorpid();
        Integer isImport = workflowTransferPOJO.getIsImport();
        Data pojoData = workflowTransferPOJO.getData();
        User user = workflowTransferPOJO.getUser();
        Long dataId = pojoData.getId();
        JSONObject newData = pojoData.getData();

        WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(workflowTransferPOJO.getBackupDataId(), corpid);
        if (Objects.isNull(workflowBackupDataEntity)) {

        }

        JSONObject oldData = workflowBackupDataEntity.getData();
        boolean isNew = false;
        boolean isRed = false;
        if(newData.containsKey(InvoiceEnum.ORIGIN_ID.getAttr())){
            Long originId = FastJsonHelper.getLongOrDefaultFromFormData(newData,InvoiceEnum.ORIGIN_ID.getAttr(),0L);
            if(originId >0){
                isRed = true;
            }
        }
        boolean isEnable = false;
        Long originId = FastJsonHelper.getLongOrDefaultFromFormData(newData, InvoiceEnum.ORIGIN_ID.getAttr(), 0L);


        if(CollectionsUtil.isEmpty(saasNeedRedundantAttrPojo.getAmountDetail()) && Objects.equals(isImport,BasicConstant.ZERO)){
            //兼容老数据,老数据走导入的老逻辑
            isImport = BasicConstant.ONE;
        }
        Object contractNoObject = newData.get(InvoiceEnum.CONTRACT_ID_LINK_TEXT.getAttr());
        List<String> contractNoList = null;
        if(Objects.nonNull(contractNoObject)){
            if(contractNoObject instanceof String[]){
                String[]  purchaseNos = (String[]) contractNoObject;
                contractNoList = new ArrayList<>(Arrays.asList(purchaseNos));
            }else if(contractNoObject instanceof List){
                contractNoList = (List<String>) contractNoObject;
            }
        }else {
            contractNoList = new ArrayList<>();
        }
        InvoiceRelationshipEditPojo invoiceRelationshipEditPojo = invoiceHelp.getAddOrDeleteRelationship(newData, oldData, corpid, dataId);
        //开票的金额
        Double totalMoney = getDoubleOrDefaultFromFormData(newData, InvoiceEnum.TOTAL_MONEY.getAttr(), 0D);
        //-------------------------------关系表存储公共的属性
        Long now = (long) DateUtil.getInt();
        Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(newData, InvoiceEnum.CUSTOMER_NAME.getAttr(), 0L);
        String customerName = FastJsonHelper.getStringOrDefaultFromFormData(newData, InvoiceEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), "");


        // 删除原先的的合同和回款关系，以后再改成批量更新方式
        invoiceRelationshipModel.deleteByInvoiceId(dataId, corpid);


        InvoiceEntityExt invoiceEntityExt = invoiceModel.getByKey(dataId, corpid);
        UserEntity userEntity = userModel.getByKey(user.getUserId(), corpid);
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(userEntity, userVO);

        InvoiceCommonSavePojo invoiceCommonSavePojo = new InvoiceCommonSavePojo(invoiceRelationshipEditPojo.getContractIdList(), corpid, dataId, originId, now,saasNeedRedundantAttrPojo, isNew, isEnable, isImport, isRed, totalMoney, saasNeedRedundantAttrPojo.getAmountDetail(), invoiceEntityExt, userVO, pojoData.getBusinessType(), pojoData.getSubBusinessType());
        boolean contractInvoiceFlag = saasNeedRedundantAttrPojo.isHasContract() && !saasNeedRedundantAttrPojo.isHasPayment() && !saasNeedRedundantAttrPojo.isHasPaymentSheet();
        boolean paymentInvoiceFlag = saasNeedRedundantAttrPojo.isHasPayment() && saasNeedRedundantAttrPojo.isHasContract() && !saasNeedRedundantAttrPojo.isHasPaymentSheet();
        boolean paymentSheetInvoiceFlag = saasNeedRedundantAttrPojo.isHasPaymentSheet() && saasNeedRedundantAttrPojo.isHasContract() && !saasNeedRedundantAttrPojo.isHasPayment();
        boolean isPrePaymentSheetFlag = saasNeedRedundantAttrPojo.isPrePaymentSheet();
//        try {
        try {
            String lang = LocaleContextHolder.getLocale().toString();
            if(saasNeedRedundantAttrPojo.isContractUnion() || contractInvoiceFlag) {
                //合同不为空 其他为空 合同合并开票
                invoiceCommonSavePojo.setRefIdList(invoiceRelationshipEditPojo.getContractIdList());
                invoiceCommonSavePojo.setRefTypeEnum(RefTypeEnum.CONTRACT);
                invoiceCommonSavePojo.setContractNos(contractNoList);
                invoiceCommonSavePojo.setCustomerId(customerId);
                invoiceCommonSavePojo.setCustomerName(customerName);
                invoiceService.invoiceCommonSaveHandle(invoiceCommonSavePojo);
            }else if(saasNeedRedundantAttrPojo.isPaymentUnion() || paymentInvoiceFlag) {
                invoiceCommonSavePojo.setRefIdList(invoiceRelationshipEditPojo.getPaymentIdList());
                invoiceCommonSavePojo.setRefTypeEnum(RefTypeEnum.PAYMENT);
                invoiceCommonSavePojo.setContractNos(contractNoList);
                invoiceCommonSavePojo.setCustomerId(customerId);
                invoiceCommonSavePojo.setCustomerName(customerName);
                invoiceService.invoiceCommonSaveHandle(invoiceCommonSavePojo);
            }else if(saasNeedRedundantAttrPojo.isPaymentSheetUnion() || paymentSheetInvoiceFlag || isPrePaymentSheetFlag) {
                invoiceCommonSavePojo.setRefIdList(invoiceRelationshipEditPojo.getPaymentSheetIdList());
                invoiceCommonSavePojo.setRefTypeEnum(RefTypeEnum.PAYMENTSHEET);
                invoiceCommonSavePojo.setContractNos(contractNoList);
                invoiceCommonSavePojo.setCustomerId(customerId);
                invoiceCommonSavePojo.setCustomerName(customerName);
                invoiceService.invoiceCommonSaveHandle(invoiceCommonSavePojo);
            }else {
                InvoiceRelationshipEntity invoiceRelationshipEntity = invoiceHelp.buildNewInvoiceRelation(false, dataId, now,customerId,customerName, corpid,totalMoney,0L,"",0L, "",0L, "",0);
                if (Objects.nonNull(invoiceRelationshipEntity)) {
                    try {
                        invoiceRelationshipModel.insert(invoiceRelationshipEntity);
                    } catch (Exception e) {
                        log.error("插入发票关系实体表出错", e);
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                    }
                }//消息推送
                invoiceHelp.invoiceMessagePushHandle(invoiceCommonSavePojo);
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowInvoiceStrategy.update 报错", e);
        }
//        } catch (XbbException e) {
//            rollBack4LinkEs(null, corpid, invoiceRelationshipEditPojo.getContractIdList(), invoiceRelationshipEditPojo.getPaymentIdList(), invoiceRelationshipEditPojo.getPaymentSheetIdList());
//            LOG.error("invoiceServiceImp.afterSave 执行出错：", e);
//            throw e;
//        }catch (Exception e){
//            rollBack4LinkEs(null, corpid, invoiceRelationshipEditPojo.getContractIdList(), invoiceRelationshipEditPojo.getPaymentIdList(), invoiceRelationshipEditPojo.getPaymentSheetIdList());
//            LOG.error("invoiceServiceImp.afterSave 执行出错：", e);
//            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
//        }

        //获取当前处于什么模式
        Long modelType = fundSetModel.getModelType(corpid,XbbRefTypeEnum.CRM);
        if(Objects.equals(modelType,ModelTypeEnum.INVOICE.getCode()) && isNew){
            if(!isRed) {
                JSONArray contractIdArray = newData.getJSONArray(InvoiceEnum.CONTRACT_ID.getAttr());
                if (CollectionsUtil.isNotEmpty(contractIdArray)) {
                    SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
                    saasFormSaveDTO.setCorpid(corpid);
                    saasFormSaveDTO.setAmountDetail(saasNeedRedundantAttrPojo.getAmountDetail());
                    saasFormSaveDTO.setNewPaasFormDataEntity(invoiceEntityExt);
                    saasFormSaveDTO.setBusinessType(pojoData.getBusinessType());
                    Map<String, List<ReturnUserAndDepartmentPojo>> resultMap = OwnerIdAndCoUserIdUtil.setOwnIdAndCoUserId(newData);
                    saasFormSaveDTO.setOwnerId(resultMap.get(FieldTypeEnum.OWNERID.getAlias()));
                    saasFormSaveDTO.setCoUserId(resultMap.get(FieldTypeEnum.COUSERID.getAlias()));
                    saasFormSaveDTO.setProcessCreatorId(user.getUserId());
                    saasFormSaveDTO.setIsImport(isImport);
                    saasFormSaveDTO.setLoginUser(userVO);

                    WorkflowReceivablesDTO workflowReceivablesDTO = new WorkflowReceivablesDTO();
                    workflowReceivablesDTO.setSaasFormSaveDTO(saasFormSaveDTO);
                    workflowReceivablesDTO.setModelType(modelType);

                    receivablesHelper.createReceivablesHandle(saasFormSaveDTO, modelType, null);
//                    receivablesHelper.createReceivablesHandle(saasFormSaveDTO, modelType, null);
                }
            }
        }

        //销项发票一致性同步，如果发票产生应收的话，下游应收款中的来源单据编号需要同步一下
        try {
            String oldInvoiceSeriNo = workflowBackupDataEntity.getData().getString(BasicConstant.SERIAL_NO);
            String newInvoiceSerialNo = newData.getString(BasicConstant.SERIAL_NO);
            if (!Objects.equals(oldInvoiceSeriNo, newInvoiceSerialNo)) {
                ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(corpid, dataId, newInvoiceSerialNo);
                consistencySyncService.syncInvoice(consistencySyncRabbitMqDTO);
            }
        }catch (Exception e){
            log.error("数据一致性同步", e);
        }

        // api
        apiHook(workflowTransferPOJO);
        // log
        afterUpdateLog(workflowTransferPOJO);
    }

    @Override
    public void updateBack(Long taskId, WorkflowTransferPOJO workflowTransferPOJO) throws XbbException{
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Long backupDataId = workflowTransferPOJO.getBackupDataId();
            Long dataId = workflowTransferPOJO.getData().getId();
            WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(workflowTransferPOJO.getBackupDataId(), corpid);
            if (Objects.nonNull(workflowBackupDataEntity)) {
                JSONObject data = workflowBackupDataEntity.getData();

                replenishAttrForBackupData(workflowTransferPOJO.getData().getData(), data);

                InvoiceEntityExt invoiceEntityExt = new InvoiceEntityExt();
                invoiceEntityExt.setId(workflowTransferPOJO.getData().getId());
                invoiceEntityExt.setCorpid(corpid);
                invoiceEntityExt.setData(data);
                invoiceEntityExt.setSerialNo(data.getString(FieldTypeEnum.SERIALNO.getAlias()));
                // 获取负责人
                invoiceEntityExt.setOwnerId(getOwnerId(data));
                invoiceEntityExt.setDepartmentId(data.getLong(FieldTypeEnum.DEPARTMENTID.getAlias()));
                invoiceEntityExt.setFormId(workflowTransferPOJO.getData().getFormId());
                FormDataUtil.removeSystemData(data);
                if (Objects.equals(workflowTransferPOJO.getOperate(), WorkflowOperateEnum.UPDATE.getType())) {
                    invoiceEntityExt.setFlowStatus(FlowStatusEnum.PASS.getType());
                }
                invoiceModel.update(invoiceEntityExt);

                // 回退被删掉的子表单
                updateBackSubForm(invoiceEntityExt, corpid, IndexTypeEnum.IDX_SAAS_INVOICE_SUB);
                //回退被删掉的富文本
                updateBackRichText(taskId, workflowTransferPOJO);

                updateBackSubForm(invoiceEntityExt, corpid, IndexTypeEnum.IDX_SAAS_INVOICE_EXPRESS);
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowInvoiceStrategy.updateBack error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public void approvalFailed(Long taskId, WorkflowTransferPOJO workflowTransferPOJO, Integer taskType) throws XbbException {
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Data workflowData = workflowTransferPOJO.getData();
            Long dataId = workflowData.getId();
            Long formId = workflowData.getFormId();
            Integer businessType = workflowData.getBusinessType();
            Integer saasMark = workflowData.getSaasMark();
            InvoiceEntityExt invoiceEntityExt = new InvoiceEntityExt();
            invoiceEntityExt.setId(dataId);
            if (Objects.equals(TaskTypeEnum.REVOKE.getType(), taskType)) {
                invoiceEntityExt.setFlowStatus(FlowStatusEnum.REVOKE.getType());
            } else {
                invoiceEntityExt.setFlowStatus(FlowStatusEnum.REJECT.getType());
            }
            invoiceEntityExt.setCorpid(corpid);
            invoiceEntityExt.setUpdateTime(DateTimeUtil.getInt());
            invoiceModel.update(invoiceEntityExt);
            // 子表单
            DelEnum del = DelEnum.APPROVE_FAILED;

            paasFormSubDataModel.deleteBatchByDataId(Collections.singletonList(dataId), corpid, IndexTypeEnum.IDX_SAAS_INVOICE_EXPRESS, del);
            paasFormSubDataModel.deleteBatchByDataId(Collections.singletonList(dataId), corpid, IndexTypeEnum.IDX_SAAS_INVOICE_SUB, del);
            //富文本
            deleteFormRichText(dataId, corpid, formId, businessType, saasMark, DelEnum.NORMAL);


        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowInvoiceStrategy.approvalFailed error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }


}
